<template>
  <el-dialog
    v-model="showDialog"
    :title="title"
    width="30%"
    :shopData="shopData"
    draggable
  >
    <el-form label-width="80px">
      <el-form-item label="商品名字">
        <el-input v-model="form.shop_name" type="text"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="desc">
        <el-input v-model="form.shop_price" type="text" />
      </el-form-item>
      <el-form-item label="商品描述" prop="desc">
        <el-input v-model="form.shop_dec" type="textarea" />
      </el-form-item>
      <el-form-item label="商品类别" prop="desc">
        <el-select v-model="form.tag" clearable placeholder="请选择">
          <el-option
            v-for="item in form.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="图片上传">
        <el-upload
          class="avatar-uploader"
          action="https://upload-z2.qiniup.com"
          :show-file-list="false"
          :http-request="upload"
          :before-upload="beforeUpload"
        >
          <img
            v-if="imageUrl"
            :src="imageUrl"
            class="avatar"
            style="width: 178px; height: 178px"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <el-icon>
              <Plus />
            </el-icon>
          </el-icon> </el-upload
      ></el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  defineProps,
  defineExpose,
  onMounted,
  reactive,
  ref,
  watch,
  defineEmits,
} from "vue";
import { getToken, uploadShop, editShop, getGoodsList } from "@/request/api";
import { formData } from "@/util/data";
import { ElMessage } from "element-plus";
import axios from "axios";
const prop = defineProps({
  shopData: Object,
  title: String,
  page: Number,
});
const pageData = {
  page: 1,
  pageSize: 10,
};
const showDialog = ref(false);
defineExpose({ showDialog });
const form = reactive(formData);

watch(
  () => prop.shopData,
  (newVal: any, oldVal: any) => {
    imageUrl.value = newVal.shop_img;
    form.shop_dec = newVal.shop_dec;
    form.tag = newVal.tag;
    form.shop_name = newVal.shop_name;
    form.shop_price = newVal.shop_price;
  },
  { deep: true }
);
const cdnDomin = "rv56kjtfi.hn-bkt.clouddn.com";
onMounted(async () => {});
const imageUrl = ref("");
// 图片上传之前
const beforeUpload = (rawFile: any) => {
  console.log(rawFile);

  if (!["image/webp", "image/png", "image/jpeg"].includes(rawFile.type)) {
    ElMessage.error("图片格式应该是png或jpg或webp");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小应该小于2MB");
    return false;
  }
  return true;
};

//图片上传
const upload = (req: any) => {
  console.log(req);

  const config = {
    headers: { "Content-Type": "multipart/form-data" },
  };

  const fileType = req.file.type.slice(6);
  // 重命名要上传的文件
  const keyname = "shop" + new Date().getTime() + "." + fileType;
  getToken().then((res) => {
    const formdata = new FormData();
    formdata.append("file", req.file);
    formdata.append("token", res.data.token);
    formdata.append("key", keyname);
    // 获取到凭证之后再将文件上传到七牛云空间
    axios.post("https://upload-z2.qiniup.com", formdata, config).then((res) => {
      imageUrl.value = "http://" + cdnDomin + "/" + res.data.key;
      console.log(res);
    });
  });
};
const emits = defineEmits(["getData"]);
const dataList = ref([]);
const count = ref(0);
const getShopList = async () => {
  const { data } = await getGoodsList(pageData);
  dataList.value = data.data;
  count.value = data.count;
};
// 提交
const onSubmit = async () => {
  const obj = {
    shop_name: form.shop_dec,
    tag: form.tag,
    shop_price: form.shop_price,
    shop_dec: form.shop_dec,
    shop_img: imageUrl.value,
    shop_id: prop?.shopData?.shop_id,
  };
  if (prop.title === "商品上传") {
    await uploadShop(obj).then(async (res: any) => {
      pageData.page = prop.page;
      ElMessage.success("上传成功");
      showDialog.value = false;
      await getShopList();
      emits("getData", dataList.value, count.value);
    });
  } else {
    await editShop(obj).then(async (res: any) => {
      pageData.page = prop.page;
      ElMessage.success("编辑成功");
      showDialog.value = false;
      await getShopList();
      emits("getData", dataList.value, count.value);
    });
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
